package com.zboin.ucenter.service.impl;

import com.zboin.common.utils.JwtUtils;
import com.zboin.ucenter.auth.SmsAuthenticationToken;
import com.zboin.ucenter.mapper.UserInfoMapper;
import com.zboin.ucenter.model.LoginBody;
import com.zboin.ucenter.model.UserInfo;
import com.zboin.ucenter.model.enums.LoginTypeEnum;
import com.zboin.ucenter.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @author zhboom
 * @date 2025/7/21 21:47
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private static final Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);

    private final AuthenticationManager authenticationManager;
    private final UserInfoMapper userInfoMapper;

    public UserInfoServiceImpl(AuthenticationManager authenticationManager, UserInfoMapper userInfoMapper) {
        this.authenticationManager = authenticationManager;
        this.userInfoMapper = userInfoMapper;
    }

    @Override
    public ResponseEntity<String> login(LoginBody loginBody) {
        if (!LoginTypeEnum.USERNAME_PASSWORD.equals(loginBody.getLoginType())) {
            logger.warn("Login type {} is not equals to [USERNAME_PASSWORD]", loginBody.getLoginType());
            return ResponseEntity.badRequest().body("Invalid login type");
        }
        try {
            Authentication authenticate = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword()));
            return responseAuthentication(authenticate);
        } catch (Exception e) {
            logger.error("Login failed", e);
            return ResponseEntity.status(401).body("login failed");
        }
    }

    @Override
    public ResponseEntity<String> smsLogin(LoginBody loginBody) {
        if (!LoginTypeEnum.PHONE_CODE.equals(loginBody.getLoginType())) {
            logger.warn("Login type {} is not equals to [USERNAME_PASSWORD]", loginBody.getLoginType());
            return ResponseEntity.badRequest().body("Invalid login type");
        }
        try {
            Authentication authenticate = authenticationManager.authenticate(
                    new SmsAuthenticationToken(loginBody.getPhone(), loginBody.getCode()));
            return responseAuthentication(authenticate);
        } catch (Exception e) {
            logger.error("SMS login failed", e);
            return ResponseEntity.status(401).body("login failed");
        }
    }

    private ResponseEntity<String> responseAuthentication(Authentication authenticate) {
        if (authenticate.isAuthenticated()) {
            Long userId = ((UserInfo) authenticate.getPrincipal()).getUserId();
            String token = JwtUtils.generateToken(String.valueOf(userId));
            return ResponseEntity.ok()
                    .body("Bearer " + token);
        } else {
            return ResponseEntity.status(401).body("login failed");
        }
    }

    @Override
    public ResponseEntity<String> logout() {
        return null;
    }
}
